package cycling.taxi.com.ui.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.LruCache;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cycling.taxi.com.IConstants;
import cycling.taxi.com.MainActivity;
import cycling.taxi.com.R;
import cycling.taxi.com.entity.AppImg;
import cycling.taxi.com.entity.Tips;
import cycling.taxi.com.eventbus.SendMassage;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.ui.fragment.ConditionFrgt;
import cycling.taxi.com.ui.fragment.InsureFrgt;
import cycling.taxi.com.ui.fragment.MyFrgt;
import cycling.taxi.com.ui.fragment.ServeFrgt;
import cycling.taxi.com.ui.fragment.StoreFrgt;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;

/**
 * Created by Administrator on 2017/4/20.
 */
public class HomeAty extends FragmentActivity implements RadioGroup.OnCheckedChangeListener,RequestCallback{

    @InjectView(R.id.home_flayout)
    FrameLayout mHomeFlayout;
    @InjectView(R.id.home_bt_condition)
    RadioButton mHomeBtCondition;
    @InjectView(R.id.home_bt_serve)
    RadioButton mHomeBtServe;
   /* @InjectView(R.id.home_bt_store)
    RadioButton mHomeBtStore;
    @InjectView(R.id.home_bt_insure)
    RadioButton mHomeBtInsure;*/
    @InjectView(R.id.home_bt_my)
    RadioButton mHomeBtMy;
    @InjectView(R.id.home_rgroup)
    RadioGroup mHomeRgroup;
    private List<AppImg> data=null;
    //volley队列
    private RequestQueue queue;
    //Fragment的缓存集合
    private Map<Integer, Fragment> fragmentCache = new HashMap<>();
    //图片存储路径
    String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cycling.taxi.com";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initUI();

        initListener();

        initData();
//        //volley队列
//        queue= Volley.newRequestQueue(this);
    //    volleyGet2();
        getImg();
    }
    //volley请求图片加载
    public void volleyGet2(String s){
        String path= Urls.getImg()+s;
        ImageLoader imageLoader = new ImageLoader(queue, new BitmapCache());
//        ImageLoader.ImageListener listener = ImageLoader.getImageListener(testImg,
//                R.drawable.splash_bg, R.drawable.splash_bg);
//        imageLoader.get(path, listener);
        imageLoader.get(path, new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                // testImg.setImageBitmap(imageContainer.getBitmap());
           //     ToastUtil.getInstance().toast(dir);
            }

            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });

    }
    public void getImg(){
        RequestParams params = new RequestParams.Builder()
                .putParam("beanJson", SPUtil.getInstance().getData("beanJson"))
                .build();
        //开始请求发送数据到服务器服务器
        queue = Volley.newRequestQueue(this);
        String url = Urls.getAppImg();//回去api路径

        RequestUtil.requestData(queue,
                IConstants.LOGIN,
                url,
                RM.GET,
                RequestBean.class,
                params,
                this);

    }

    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.e("requestSuccess数据="+bean.beanJson);
        if(bean.getStatus().equals("0")) {
            data = new Gson().fromJson(bean.beanJson, new TypeToken<List<AppImg>>(){}.getType());
            for(int i=0;i<data.size();i++) {
                deletPictures();
                volleyGet2(data.get(i).getAppimgUrl());
            }
        }else {
            deletPictures();
        }
    }

    @Override
    public void requestFail(RequestBean bean, Config config) {
        LogUtil.e("requestSuccess数据="+"错误");
        deletPictures();
    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {

    }
    public List<String> getPictures(final String strPath) {
        List<String> list = new ArrayList<String>();
        File file = new File(strPath);
        File[] allfiles = file.listFiles();
        if (allfiles == null) {
            return null;
        }
        for (int k = 0; k < allfiles.length; k++) {
            final File fi = allfiles[k];
            if (fi.isFile()) {
                int idx = fi.getPath().lastIndexOf(".");
                if (idx <= 0) {
                    continue;
                }
                String suffix = fi.getPath().substring(idx);
                if (suffix.toLowerCase().equals(".jpg") ||
                        suffix.toLowerCase().equals(".jpeg") ||
                        suffix.toLowerCase().equals(".bmp") ||
                        suffix.toLowerCase().equals(".png") ||
                        suffix.toLowerCase().equals(".gif")) {
                    list.add(fi.getPath());
                }
            }
        }
        return list;
    }
    public void deletPictures(){
        List<String> pathlist=getPictures(dir);

        for(int i=0;i<pathlist.size();i++){
            File fi=new File(pathlist.get(i));
            fi.delete();
        //    ToastUtil.getInstance().toast("delete");
        }
    }
    //图片缓存
    public class BitmapCache implements ImageLoader.ImageCache {

        private LruCache<String, Bitmap> mCache;

        public BitmapCache() {
            int maxSize = 10 * 1024 * 1024;
            mCache = new LruCache<String, Bitmap>(maxSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            };
        }

        /**
         * 先从缓存中找，有则返回图片，没有则从网络获取
         */
        @Override
        public Bitmap getBitmap(String url) {
            /**
             * 先从缓存中找，有则返回，没有则返回null
             */
            Bitmap bitmap = mCache.get(url);

            if (bitmap == null) {
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                /**
                 * 如果为null，则缓存中没有，从本地SD卡缓存中找
                 */
                File cacheDir = new File(dir);
                File[] cacheFiles = cacheDir.listFiles();
                if (cacheFiles != null) {
                    int i = 0;
                    for (; i < cacheFiles.length; i++) {
                        if (TextUtils.equals(fileName, cacheFiles[i].getName()))
                            break;
                    }
                    /**
                     * 若找到则返回bitmap否则返回null
                     */
                    if (i < cacheFiles.length) {
                        bitmap = getSDBitmap(dir + "/"
                                + fileName);
                        /**
                         * 将从SD卡中获取的bitmap放入缓存中
                         */
                        mCache.put(url, bitmap);
                    }
                }
            }
            return bitmap;
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            /**
             * 放入缓存中
             */
            mCache.put(url, bitmap);
            /**
             * 存到本地SD中
             */
            putSDBitmap(url.substring(url.lastIndexOf("/") + 1), bitmap);
        }

        /**
         * 从本地SD卡中获取图片
         *
         * @param imgPath
         *            图片路径
         * @return 图片的Bitmap
         */
        private Bitmap getSDBitmap(String imgPath) {
            Bitmap bm = null;
            BitmapFactory.Options options = new BitmapFactory.Options();
            /**
             * 设置临时缓存大小
             */
            options.inTempStorage = new byte[1024 * 1024];
            /**
             * 通过设置Options.inPreferredConfig值来降低内存消耗： 默认为ARGB_8888: 每个像素4字节. 共32位。
             * Alpha_8: 只保存透明度，共8位，1字节。 ARGB_4444: 共16位，2字节。 RGB_565:共16位，2字节
             */
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            /**
             * inPurgeable:设置为True,则使用BitmapFactory创建的Bitmap用于存储Pixel的内存空间，
             * 在系统内存不足时可以被回收，当应用需要再次访问该Bitmap的Pixel时，系统会再次调用BitmapFactory
             * 的decode方法重新生成Bitmap的Pixel数组。 设置为False时，表示不能被回收。
             */
            options.inPurgeable = true;
            options.inInputShareable = true;
            /**
             * 设置decode时的缩放比例。
             */
            options.inSampleSize = 1;
            bm = BitmapFactory.decodeFile(imgPath, options);
            return bm;
        }

        /**
         * 将图片保存到本地的SD卡中
         *
         * @param fileName
         * @param bitmap
         */
        private void putSDBitmap(final String fileName, final Bitmap bitmap) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    File cacheDir = new File(dir);
                    if (!cacheDir.exists())
                        cacheDir.mkdirs();
                    File cacheFile = new File(dir + "/"
                            + fileName);
                    if (!cacheFile.exists()) {
                        try {
                            cacheFile.createNewFile();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(cacheFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }
    private void initData() {
        mHomeRgroup.check(R.id.home_bt_condition);
    }

    private void initListener() {
        mHomeRgroup.setOnCheckedChangeListener(this);
    }

    private void initUI() {
        setContentView(R.layout.aty_home);
        ExitApplication.getInstance().addActivity(this);
        ButterKnife.inject(this);

    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Fragment fragment=null;
        //判断fragment是否有缓存e
        if (fragmentCache != null && fragmentCache.size() != 0 && fragmentCache.get(checkedId) != null){
            fragment=fragmentCache.get(checkedId);
        }else {

            switch (checkedId) {
                case R.id.home_bt_condition://车况
                    fragment=new ConditionFrgt();
                    break;
                case R.id.home_bt_serve://服务
                    fragment=new ServeFrgt();
                  //  myTouchListeners.remove();
                    break;
            /*    case R.id.home_bt_store://商城
                    fragment=new StoreFrgt();
                    break;
                case R.id.home_bt_insure://保险
                    fragment=new InsureFrgt();
                    break;*/
                case R.id.home_bt_my://我的
                    fragment=new MyFrgt();
                    break;
            }

            if (fragment==null){
                return;
            }
//            将fragment存入缓存
            fragmentCache.put(checkedId, fragment);
        }
//        用甄布局替换Fragment

        getSupportFragmentManager().beginTransaction().replace(R.id.home_flayout, fragment).commit();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().post(new SendMassage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.reset(this);
    }




    public interface MyTouchListener {
        public void onTouchEvent(MotionEvent event);
    }

    // 保存MyTouchListener接口的列表
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<HomeAty.MyTouchListener>();

    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     * @param listener
     */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     * @param listener
     */
    public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove( listener );
    }

    /**
     * 分发触摸事件给所有注册了MyTouchListener的接口
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

}
